const app = getApp()

Page({
  data: {
    loading: true,
    page: 0,
    active: 0,
    tabs: [],
    coupon:[],
    keyword:''
  },
  //监听页面记载
  onLoad:function () {
    this.getCate();
  },
  //底部加载更多
  onReachBottom: function () {
    this.setData({
      loading: true,
    });
    this.getCoupon();
  },
  //行业分类
  getCate: function () {
    var param = {
      'signkey': app.util().getRandom(12),
      'cate_id': 0,
      'lists': 1
    }
    app.api().Get('api/v4/allwin/store/cate', param, (result) => {
      if (result.code == 200) {
        this.setData({
          tabs: result.data,
          active: result.data[0].id,
        })
        this.getCoupon();
      }
    })
  },
  //读取优惠券
  getCoupon: function () {
    if (this.data.loading) {
      var param = {
        types: 0,
        cate_id: this.data.active,
        page: this.data.page + 1,
        keyword: this.data.keyword,
      }
      app.api().Get('api/v4/allwin/coupon/couponList',param,(result) => {
        if (result.code == 200) {
          var coupon = this.data.coupon;
          for (let i in result.data) {
            coupon.push(result.data[i]);
          }
          this.setData({
            coupon: coupon,
            page: param.page,
          });
        }
      })
    }
    this.setData({
      loading: false
    })
  },
  //切换栏目
  onTabs: function (event) {
    this.setData({
      active: event.detail.name,
      loading: true,
      page:0,
      coupon: [],
    })
    this.getCoupon();
  },
  //领取优惠券
  onCoupon: function (e) {
    var coupon_id = e.currentTarget.id;
    var coupon_key = e.currentTarget.dataset.key;
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    var parms = {
      signkey: app.util().getRandom(12),
      coupon_id: coupon_id
    }
    app.api().Post('api/v4/allwin/coupon/buyCoupon', parms, (rel) => {
      var coupon = this.data.coupon;
      if (rel.data.isbuy == 0) {
        app.doWechatPay(rel.data.pay, (res) => {
          coupon[coupon_key]['state'] = 1;
          this.setData({
            coupon: coupon,
          })
        }, (res) => {
          wx.showToast({ title: '领取失败', icon: 'none' })
        });
      } else {
        wx.showToast({ title: '领取成功', icon: 'success' })
        coupon[coupon_key]['state'] = 1;
        this.setData({
          coupon: coupon,
        })
      }
      wx.hideLoading();
    })
  },
  //搜索
  onSearch:function(event) {
    var keyword = '';
    if (app.util().isNull(event.detail)){
      app.wxAlert('请输入优惠券关键词');
    }else{
      keyword = event.detail;
    }
    this.setData({
      loading: true,
      page: 0,
      coupon: [],
      keyword: keyword,
    })
    this.getCoupon();
  },
})